<template>
  <div class="mform-setting-photo-article-list">
    
    <div class="mform-setting-photo-article-list-header">
      <span class="mform-setting-photo-article-list-header-title">
        {{ title }}
      </span>
      <span class="mform-setting-photo-article-list-header-subtitle">
        {{ subTitle }}
      </span>
    </div>
    
    <div class="mform-setting-photo-article-list-block">
      <draggable
        animation="180"
        class="nested-draggable"
        tag="div" 
        :list="lists"
        filter=".undraggable"
        @end="draggableEndHandler"
        v-if="currentInputFocusIndex === null"
      >
        <div 
          class="mform-setting-photo-article-list-item"
          :class="{ undraggable: currentInputFocusIndex === index}"
          v-for="(item, index) in lists"
          :key="index"
        >
          <div class="mform-setting-photo-article-list-item-header">
            <span class="mform-setting-photo-article-list-item-header-title">
              导航 {{ index + 1}}
            </span>
            <span v-if="lists.length > 1" class="mform-setting-photo-article-list-item-header-delete" @click="deleteItem(index)">
              删除
            </span>
          </div>
          
          <div class="mform-setting-photo-article-list-item-content">
            <div class="mform-setting-photo-article-list-content-image" v-if="isShowImage">
              <div
                v-if="formType === 'imageTextNavigation'"
                class="replace-image"
                @click="openReplaceImageDialog(item.imageUrl, index)"
              >
                <mform-setting-mark text="更换图片" v-if="item.imageUrl">
                  <img :src="item.imageUrl" class="avatar" />
                </mform-setting-mark>
                <i class="el-icon-plus" v-else></i>
              </div>
              <el-upload
                v-else
                action="string"
                :on-preview="handlePictureCardPreview"
                :before-upload="onBeforeUploadImage"
                :http-request="uploadImagePicBefore(index)"
                :limit="10000"
                accept=".jpg,.jpeg,.png"
              >
                <mform-setting-mark text="更换图片" v-if="item.imageUrl">
                  <img :src="item.imageUrl" class="avatar">
                </mform-setting-mark>
                <i class="el-icon-plus" v-else></i>
              </el-upload>
            </div>
            
            <div class="mform-setting-photo-article-list-content-main">
              <mform-item :label="titleField.displayName">
                <form-text 
                  @focus="handlerTitleFocus(index)" 
                  @blur="handlerTitleBlur($event)" 
                  :value="item.title" 
                  :field="titleField" 
                  @input="(value) => updateTitle(value, index)" 
                />
                <!-- <div class="language-config" @click="openMultilinguaDialog(index)" v-if="isOpenMultiLanguage">
                  <i class="iconfont icon-earth"></i>
                </div> -->
                <div v-if="isOpenMultiLanguage">
                  <base-select-language 
                    :selectKey="index"
                    :field="titleField"
                    :defaultOption="{
                      formType:'text',
                    }"
                    defaultFormType="text"
                    :defaultValue="lists[index].title"
                    :defaultValueLanguage="lists[index].titleLanguage"
                    :isFill="false"
                    @save="updateFields"
                  >
                  </base-select-language>
                </div>
              </mform-item>
              
              <mform-item :label="linkField.displayName">
                <form-select
                  :clearable="false"
                  :field="linkField"
                  :value="item.urlType"
                  :source="dataSource"
                  @input="(value) => updateUrlType(value, index)"
                />
              </mform-item>
              <div 
                v-if="isOpenMultiLanguage && item.urlType === 'event'"
                class="event-link"
              >
                如需多语言，可<span @click="handleJump">前往事件类型</span>配置
              </div>
              
              <mform-item
                v-if="showCustomLinkInput(item)"
                :label="linkCustomField.displayName"
                class="custom-link-item"
              >
                <form-text
                  @focus="handlerTitleFocus(index)"
                  @blur="handlerTitleBlur($event)"
                  :field="linkCustomField"
                  :value="item.urlAddress"
                  :placeholder="linkCustomField.placeholder"
                  @input="value => updateUrlAddress(value, index)"
                />
              </mform-item>
              
              <mform-item v-if="showEventListSelect(item)">
                <form-select
                  :field="linkField"
                  :value="item.eventId"
                  :source="eventDataSource"
                  @input="(value) => updateEvent(value, index)"
                  placeholder="[必选]请选择事件类型"
                />
              </mform-item>
              <mform-item v-if="showWikiListSelect(item) && item.eventId && item.urlAddress && !value[index].wikiIds.length && isShowOldWiki(item.eventId)">
                <el-input
                  :value="getWikiTit(item.eventId)"
                  readonly
                />
              </mform-item>

              <!-- 知识库选择 -->
              <mform-item v-if="showWikiListSelect(item)">
                  <el-button
                    style="width:100%"
                    plain 
                    @click="openWiki(index, item.id)"
                  >
                    {{ value[index].wikiIds | wikiNum(that, item.id) }}
                  </el-button>
              </mform-item>
              <mform-item v-if="showWikiListSelect(item)">
                <div>
                  <el-checkbox
                    class="notshow-title"
                    :value="value[index].isShowWikiType"
                    @input="updateStatus($event, index)"
                  >
                  在门户中显示知识库目录
                  </el-checkbox>
                </div>
              </mform-item>
               <!-- 故障库选择 -->
              <mform-item v-if="isShowFaultLibrary(item)">
                <el-button
                  style="width:100%"
                  plain 
                  @click="openFaultLibrary(index)"
                >
                {{ value[index].faultLibraryIds.length > 0 ? $t('component.faultLibraryDialog.haveFaultLibraryTips', { data: value[index].faultLibraryIds.length}) : $t('component.faultLibraryDialog.choosePlaceholder')}}
                </el-button>
            </mform-item>
            </div>
          </div>
          
        </div>
      </draggable>
      <div 
          v-else
          class="mform-setting-photo-article-list-item"
          v-for="(item, index) in lists"
          :key="index"
        >
          <div class="mform-setting-photo-article-list-item-header">
            <span class="mform-setting-photo-article-list-item-header-title">
              导航 {{ index + 1}}
            </span>
            <span v-if="lists.length > 1" class="mform-setting-photo-article-list-item-header-delete" @click="deleteItem(index)">
              删除
            </span>
          </div>
          
          <div class="mform-setting-photo-article-list-item-content">
            <div class="mform-setting-photo-article-list-content-image" v-if="isShowImage">
              <div
                v-if="formType === 'imageTextNavigation'"
                class="replace-image"
                @click="openReplaceImageDialog(item.imageUrl, index)"
              >
                <mform-setting-mark text="更换图片" v-if="item.imageUrl">
                  <img :src="item.imageUrl" class="avatar" />
                </mform-setting-mark>
                <i class="el-icon-plus" v-else></i>
              </div>
              <el-upload
                v-else
                action="string"
                :on-preview="handlePictureCardPreview"
                :before-upload="onBeforeUploadImage"
                :http-request="uploadImagePicBefore(index)"
                :limit="10000"
                accept=".jpg,.jpeg,.png"
              >
                <mform-setting-mark text="更换图片" v-if="item.imageUrl">
                  <img :src="item.imageUrl" class="avatar">
                </mform-setting-mark>
                <i class="el-icon-plus" v-else></i>
              </el-upload>
            </div>
            
            <div class="mform-setting-photo-article-list-content-main">
              <mform-item :label="titleField.displayName">
                <form-text @focus="handlerTitleFocus(index)" @blur="handlerTitleBlur()" :value="item.title" :field="titleField" @input="(value) => updateTitle(value, index)" />
                <!-- <div class="language-config" @click="openMultilinguaDialog(index)" v-if="isOpenMultiLanguage">
                  <i class="iconfont icon-earth"></i>
                </div> -->
                <div v-if="isOpenMultiLanguage">
                  <base-select-language
                    :selectKey="index"
                    :field="titleField"
                    :defaultOption="{
                      formType:'text',
                    }"
                    defaultFormType="text"
                    :defaultValue="lists[index].title"
                    :defaultValueLanguage="lists[index].titleLanguage"
                    :isFill="false"
                    @save="updateFields"
                  >
                  </base-select-language>
                </div>
              </mform-item>
              
              <mform-item :label="linkField.displayName">
                <form-select
                  :clearable="false"
                  :field="linkField"
                  :value="item.urlType"
                  :source="dataSource"
                  @input="(value) => updateUrlType(value, index)"
                />
              </mform-item>
              <div 
                v-if="isOpenMultiLanguage && item.urlType === 'event'"
                class="event-link"
              >
                如需多语言，可<span @click="handleJump">前往事件类型</span>配置
              </div>
              
              <mform-item v-if="showCustomLinkInput(item)" :label="linkCustomField.displayName" class="custom-link-item">
                <form-text @focus="handlerTitleFocus(index)" @blur="handlerTitleBlur()" :field="linkCustomField" :value="item.urlAddress" :placeholder="linkCustomField.placeholder" @input="(value) => updateUrlAddress(value, index)" />
              </mform-item>
              
              <mform-item v-if="showEventListSelect(item)">
                <form-select
                  :field="linkField"
                  :value="item.eventId"
                  :source="eventDataSource"
                  @input="(value) => updateEvent(value, index)"
                  placeholder="[必选]请选择事件类型"
                />
              </mform-item>
              <mform-item v-if="showWikiListSelect(item) && item.eventId && item.urlAddress && !value[index].wikiIds.length && isShowOldWiki(item.eventId)">
                <!-- <form-select
                  :field="linkField"
                  :value="item.eventId"
                  :source="wikiDataSource"
                  @input="(value) => updateWiki(value, index)"
                  placeholder="请选择知识库文章"
                  disabled
                /> -->
                <el-input
                  :value="getWikiTit(item.eventId)"
                  readonly
                />
              </mform-item>
              <!-- 知识库选择 -->
              <mform-item v-if="showWikiListSelect(item)">
                  <el-button
                    style="width:100%"
                    plain 
                    @click="openWiki(index)"
                  >
                    {{ value[index].wikiIds | wikiNum(that, item.id) }}
                  </el-button>
              </mform-item>
              <mform-item v-if="showWikiListSelect(item)">
                <div>
                  <el-checkbox
                    class="notshow-title"
                    :value="value[index].isShowWikiType"
                    @input="updateStatus($event, index)"
                  >
                  在门户中显示知识库目录
                  </el-checkbox>
                </div>
              </mform-item>
              <mform-item v-if="isShowFaultLibrary(item)">
                <el-button
                  style="width:100%"
                  plain 
                  @click="openFaultLibrary(index)"
                >
                {{ value[index].faultLibraryIds.length > 0 ? $t('component.faultLibraryDialog.haveFaultLibraryTips', { data: value[index].faultLibraryIds.length}) : $t('component.faultLibraryDialog.choosePlaceholder')}}
                </el-button>
            </mform-item>
            </div>
          </div>
          
        </div>
    </div>
    
    <el-button 
      v-if="!isMax" 
      icon="el-icon-plus" 
      class="mform-setting-photo-article-list-item-add-button" 
      plain 
      type="primary" 
      @click="add"
    >
      添加
    </el-button>
    
    <!-- 图标替换弹出框 -->
    <MFormSettingReplaceImageDialog
      ref="replaceImageDialogRef"
      :graphic-init-image="graphicInitImage"
      @updateReplaceImageUrl="updateReplaceImageUrl"
    />

    <!-- 多语配置弹出框 -->
    <MultilingualDialog 
      ref="multilingualDialogRef"
      title="多语配置"
      :language-list="languageList"
      @update="updateFields"
    />
    <!-- 选择知识库弹框 -->
    <WikiDialog
      ref="wikiDialogRef"
      :documentTree='documentTree'
      :wikiIds='value[wikiIndex] && value[wikiIndex].wikiIds || []'
      :num='(value[wikiIndex] && value[wikiIndex].wikiIds || []) | wikiNum(that, wikiCurrentId)'
      :allIds="allIds"
      :isExpand="isExpand"
      @update="changeWiki($event)"
      @search="searchWiki($event)"
      @clear="clearWiki()"
    />
    <!-- 故障库弹出框 -->
    <FaultLibraryDialog ref="faultLibraryRef"
      :defaultCheckedKeys="faultLibraryIds"
      @onSubmit="onUpdateFaultLibrary">
    </FaultLibraryDialog>
  </div>
</template>

<script>
/* component */
import draggable from 'vuedraggable'
/* model */
import { getFormSettingImageTitleField, getFormSettingImageLinkField, getFormSettingImageCustomLinkField } from '@src/mform/model/MFormSettingFields.ts'
/* util */
import Uploader from 'packages/BaseUpload/uploader'
import _ from 'lodash'
import { getRootWindow } from '@src/util/dom';
/* components */
import MFormSettingMark from '@src/mform/common/setting/MFormSettingMark.vue'
import MFormSettingReplaceImageDialog from '@src/mform/common/setting/MFormSettingReplaceImageDialog.vue'
import MultilingualDialog from '@src/component/compomentV2/MultilingualDialog/index.vue';
import WikiDialog from '@src/component/compomentV2/WikiDialog/index.vue';
import { transformI18n } from '@src/locales/index.ts'
import FaultLibraryDialog from '@src/component/compomentV2/FaultLibraryDialog/index.vue';
// API
import { getDocumentTree } from '@src/api/Repository';
import { gjudgeWikiStatus } from '@src/api/PortalApi';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
import { getLocalesOssUrl } from '@src/util/assets'
const productRegisterImage = getLocalesOssUrl('/productRegister2.png')

export default {
  name: 'mform-setting-photo-article-list',
  inject: ['addNeedServerDeleFiles'],
  props: {
    subTitle: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    value: {
      type: Array,
      default: () => []
    },
    eventList: {
      type: Array,
      default: () => []
    },
    wikiList: {
      type: Array,
      default: () => []
    },
    isShowEventSelect: {
      type: Boolean,
      default: false
    },
    isOpenRegister: {
      type: Boolean,
      default: false
    },
    max: {
      type: Number,
      default: 10
    },
    titleName: {
      type: String,
      default: '标题'
    },
    formType: {
      type: String,
      default: ''
    },
    linkName: {
      type: String,
      default: '关联'
    },
    isShowImage: {
      type: Boolean,
      default: true
    },
    isValidateTitle: {
      type: Boolean,
      default: false
    },
    isValidateUrl: {
      type: Boolean,
      default: false
    },
    titleMaxlength: {
      type: Number,
      default: 10
    },
    languageList: {
      type: Array,
      default: () => [],
    },
    isOpenMultiLanguage: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      graphicInitImage: [
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/previewGraphic1.png',
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/previewGraphic2.png',
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/previewGraphic3.png',
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/previewGraphic4.png',
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/previewGraphic5.png',
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/previewGraphic6.png',
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/previewGraphic7.png',
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/previewGraphic8.png'
      ],
      portalCardDefaultImage: [
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/portalCardDefaultImage1.png',
        'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/portalCardDefaultImage2.png'
      ],
      portalAdDefaultImage: 'https://shb-pro.oss-cn-hangzhou.aliyuncs.com/shb-resource/linkc-homeIcon/portalAdDefaultImage.png',
      currentInputFocusIndex: null,
      productRegisterImage,
      replaceImageIndex: 0,
      multilingualIndex: 0,
			documentTree: null,
      wikiIndex: 1,
      wikiCurrentId: null,
      allIds: [],
      nums: {},
      that: this,
      isExpand: false,
      faultLibraryIds: [],
    }
  },
  watch: {
    currentInputFocusIndex(val,oldVal) {
      this.currentInputFocusIndex = val
    }
  },
  filters: {
    wikiNum(list, that, id) {
      let word = '选择知识库文档'
      let numList = []
      if (list && list.length) {
        numList = list.filter(item=> typeof item === 'string')
      }
      if (that.nums.hasOwnProperty(id)) {
        if (that.nums[id] !== 0) {
          word = `已选 ${that.nums[id]} 篇`
        }
      } else if (numList.length) {
        word = `已选 ${numList.length} 篇`
      }
      return word
    }
  },
  computed: {
    dataSource() {
      let source = [
        {
          text: '无链接',
          value: 'none'
        },
        {
          text: '自定义链接',
          value: 'custom'
        }
      ]
      
      if (this.isShowEventSelect) {
        source.push({
          text: '事件类型',
          value: 'event'
        }, {
          text: '进度查询 （点击后可查看服务列表）',
          value: 'query'
        })
      }

      if (this.isOpenRegister) {
        source.push({
          text: '产品注册',
          value: 'register'
        })
      }

      if (this.formType === 'contentCard' || this.formType === 'imageTextNavigation') {
        source.push({
          text: '知识库',
          value: 'wiki'
        })
      }
      if (this.formType === 'imageTextNavigation' && this.isShowFaultLibraryGray) {
        source.push({
          text: this.$t('common.form.type.faultLibrary'),
          value: 'faultLibrary'
        })
      }
      
      return source
    },
    eventDataSource() {
      return this.eventList.map(event => {
        return {
          text: event.name,
          value: event.id
        }
      })
    },
    wikiDataSource() {
      return this.wikiList.map(wiki => {
        return {
          text: wiki.title.length > 26 ? `${wiki.title.substring(0, 26)}...` : wiki.title,
          value: wiki.id
        }
      })
    },
    isMax() {
      return this.value.length >= this.max
    },
    lists() {
      // 初次添加组件默认设置默认内容
      if (this.formType === 'imageTextNavigation' && this.value.length === 0) {
        const arr = [];
        const titleArr = ['一', '二', '三', '四']
        for (let i = 0; i < 4; i++) {
          arr.push({
            urlAddress: '',
            title: `导航${titleArr[i]}`,
            titleLanguage: _.cloneDeep(this.getImageTitleLanguage(i + 1)),
            urlType: 'none',
            imageUrl: this.graphicInitImage[i],
            eventId: '',
            wikiIds: [],
            faultLibraryIds: [],
            isShowWikiType: true,
          })
        }

        this.update(arr);
        return arr;
      } else if (this.formType === 'contentCard' && this.value.length === 0) {
        const arr = [];
        for (let i = 0; i < 2; i++) {
          arr.push({
            urlAddress: '',
            title: '',
            titleLanguage: {},
            urlType: 'none',
            imageUrl: this.portalCardDefaultImage[i],
            eventId: '',
            wikiIds: [],
            isShowWikiType: true,
          })
        }

        this.update(arr);
        return arr;
      } else if (this.formType === 'pictureAD' && this.value.length === 0) {
        const arr = [];
        arr.push({
          urlAddress: '',
          title: '',
          titleLanguage: {},
          urlType: 'none',
          imageUrl: this.portalAdDefaultImage,
          eventId: ''
        })

        this.update(arr);
        return arr;
      } else if (this.formType === 'productRegister' && this.value.length === 0) {
        const arr = [];
        arr.push({
          urlAddress: '',
          title: '',
          titleLanguage: {},
          urlType: 'none',
          imageUrl: this.productRegisterImage,
          eventId: ''
        })

        this.update(arr);
        return arr;
      }

      return this.value
    },
    linkField() {
      return getFormSettingImageLinkField(this.linkName, false)
    },
    linkCustomField() {
      return getFormSettingImageCustomLinkField(this.isValidateUrl)
    },
    titleField() {
      return getFormSettingImageTitleField(this.titleName, this.isValidateTitle, this.titleMaxlength)
    },
    // 故障库灰度
    isShowFaultLibraryGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.NEW_FAULT_LIBRARY || false
    },
  },
  mounted() {
    this.gjudgeWikiStatus()
  },
  methods: {
    /** 更新故障树数据 */
    onUpdateFaultLibrary(value, index) {
      let lists = _.cloneDeep(this.lists)
      lists[index].faultLibraryIds = value
      this.update(lists)
    },
    /**打开故障库 */
    openFaultLibrary(index){
      this.faultLibraryIds = this.lists[index]?.faultLibraryIds ?? [];
      this.$refs.faultLibraryRef.openDialog(index);
      this.$refs.faultLibraryRef.selectedFaultLibrary = this.faultLibraryIds;
    },
    gjudgeWikiStatus() {
      let arry = []
      this.value.map(item => {
        if (item.urlType === 'wiki' && item.wikiDoIds.length) {
          let obj = {
            id: item.id,
            wikiDoIds: item.wikiDoIds
          }
          arry.push(obj)
        }
      })
      gjudgeWikiStatus(arry).then(res => {
        if (res.success) {
          this.nums = res.data
        }
      })
    },
    // 取老的配置的知识库标题
    getWikiTit(id) {
      let arry = this.wikiDataSource.filter(wiki => wiki.value === id)
      return arry && arry.length ? arry[0].text : id
    },
    //知识库老数据兼容
    isShowOldWiki(id){
      let arry = this.wikiDataSource.filter(wiki => wiki.value === id) || [];
      return arry.length > 0 && arry?.[0]?.text;
    },
    openWiki(index, id) {
      this.$refs.wikiDialogRef.openDialog();
		  this.getDocumentTypes();
      this.wikiIndex = index
      this.wikiCurrentId = id
    },
    add() {
      let list = _.cloneDeep(this.lists)

      list.push({
        urlAddress: '',
        title: '',
        titleLanguage: {},
        urlType: 'none',
        imageUrl: '',
        eventId: '',
        isShowWikiType: true,
        wikiIds: [],
        faultLibraryIds: [],
      })
      
      // 添加图文导航会自动添加图片
      if (this.formType === 'imageTextNavigation') {
        const length = list.length;
        list[length - 1].imageUrl = this.graphicInitImage[0];
      }
      
      this.update(list)
    },
    deleteItem(index) {
      let lists = _.cloneDeep(this.lists)
      lists.splice(index, 1)
      this.update(lists)
    },
    getImageTitleLanguage(index) {
      const titleLanguage = {};
      this.languageList.forEach(v => {
        titleLanguage[v.language] = transformI18n(
          `portal.navigation${index}`,
          v.code || v.language
        );
      });
      return titleLanguage;
    },
    draggableEndHandler() {
      this.$nextTick(() => {
        this.update(_.cloneDeep(this.lists))
      })
    },
    handlePictureCardPreview (file) {
      this.$previewElementImg(file.url)
    },
    onBeforeUploadImage (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isJPG) {
        this.$message.error('上传图片只能是 jpg/png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2mb!');
      }
      
      return isJPG && isLt2M;
    },
    showCustomLinkInput(item) {
      return item.urlType == 'custom'
    },
    showEventListSelect(item) {
      return item.urlType == 'event'
    },
    showWikiListSelect(item) {
      return item.urlType == 'wiki'
    },
    /**是否显示故障库 */
    isShowFaultLibrary(item) {
      return item.urlType == 'faultLibrary'
    },
    uploadImagePicBefore(index) {
      return (params) => {
        this.uploadImagePic(params, index)
      }
    },
    uploadImagePic(param, index) {
      Uploader.upload(param.file, '/files/upload')
        .then((result) => {
          if (result.status != 0) {
            this.$message({
              message: `${result.message}`,
              duration: 1500,
              type: 'error',
            });
            return;
          }
          
          let file = result.data;
          let item = {
            uid: param.file.uid,
            id: file.id,
            filename: file.fileName,
            // 如果后端返回url,必须使用。如果后端不返回，需要拼接
            url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
            fileSize: file.fileSizeStr,
          }
          
          let lists = _.cloneDeep(this.lists)
          this.addNeedServerDeleFiles([lists[index]?.imageUrl]);
          lists[index].imageUrl = item.url;
          this.update(lists)
        })
        .catch((err) => {
          console.warn(err)
        })
        .finally(() => { 
          // 
        })
    },
    updateReplaceImageUrl(value) {
      let lists = _.cloneDeep(this.lists)
      lists[this.replaceImageIndex].imageUrl = value
      this.update(lists)
    },
    updateUrlType(value, index) {
      let lists = _.cloneDeep(this.lists)
      lists[index].urlType = value
      if(value == 'none') {
        lists[index].urlAddress = ''
      }
      this.update(lists)
    },
    updateUrlAddress(value, index) {
      let lists = _.cloneDeep(this.lists)
      lists[index].urlAddress = value
      this.update(lists)
    },
    updateTitle(value, index) {
      let lists = _.cloneDeep(this.lists)
      lists[index].title = value
      this.$set(lists[index].titleLanguage, 'zh', value);
      // lists[index].titleLanguage['zh'] = value
      this.update(lists)
    },
    updateEvent(value, index) {
      let lists = _.cloneDeep(this.lists)
      lists[index].eventId = value
      this.update(lists)
    },
    updateWiki(value, index) {
      let lists = _.cloneDeep(this.lists)

      const protocol = window.location.protocol;
      const host = window.location.host;
      lists[index].urlAddress = `${protocol}//${host}/v_open/wiki/view?wikiId=${value}`
      lists[index].eventId = value

      this.update(lists)
    },
    update(value) {
      this.$emit('input', value)
    },
    handlerTitleFocus(index) {
      this.currentInputFocusIndex = index
    },
    handlerTitleBlur(event) {
      if (event !== 'input') {
        this.currentInputFocusIndex = null
      }
    },
    openReplaceImageDialog(imageUrl, index) {
      this.$refs.replaceImageDialogRef.openDialog(imageUrl);
      this.replaceImageIndex = index;
    },
    handleJump() {
      // this.$platform.openTab({
      //   close: true,
      //   url: '/setting/serviceStation/eventType',
      //   title: '系统管理'
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServiceStation,
        titleKey: '系统管理'
      })
    },
    openMultilinguaDialog(index) {
      this.multilingualIndex = index;
      // 给图文导航组件添加默认值
      // if (
      //   this.formType === 'imageTextNavigation' &&
      //   Object.keys(this.lists[index].titleLanguage).length === 0
      // ) {
      //   this.lists[index].titleLanguage = this.imageTitleLanguage;
      // }
      if (this.lists[index].titleLanguage?.['zh'] !== this.lists[index].title) {
        const _value = _.cloneDeep(this.lists[index].titleLanguage);
        _value['zh'] = this.lists[index].title;
        this.$refs.multilingualDialogRef.openDialog(_value);
      } else {
        this.$refs.multilingualDialogRef.openDialog(this.lists[index].titleLanguage);
      }
    },
    updateFields(value, index) {
      this.multilingualIndex = index;
      let lists = _.cloneDeep(this.lists)
      lists[this.multilingualIndex].title = value['zh']
      lists[this.multilingualIndex].titleLanguage = value
      this.update(lists)
    },
    /**
		 * 获取文档
		 */
		async getDocumentTypes(keyWordEnhance = '', isExpand = false) {
      let that = this
      let params = {
          keyWordEnhance,
          view: 'published',
          allowShare: 1,
          draft: 0
      }
			try {
				const res = await getDocumentTree(params);
          if(res.success) {
					this.documentTree = res.result || [];
          this.allIds = that.getIds(res.result || [])
          this.isExpand = isExpand
				} else {
          this.$platform.notification({
					  title: res.message,
					  type: 'error',
					});
				}
			} catch (err) {
				if (err && err.message) {
          console.log(err.message)
				}
			}
		},
    searchWiki(keyWordEnhance, isExpand = true) {
      this.getDocumentTypes(keyWordEnhance)
    },
    clearWiki() {
      this.getDocumentTypes()
    },
    // 获取所有的id
    getIds(data) {
      let res = [];
      for (let i = 0; i < data.length; i++) {
        const oItem = data[i];
        if (oItem.type === '1') {
            // return [oItem.id];
            res.push(oItem.id)
        } else {
            if (oItem.children && oItem.children.length) {
                const result = this.getIds(oItem.children);
                if (result) {
                    // return [oItem.id].concat(result);
                    res = [...res, oItem.id, ...result]
                }
            } else {
              // ? 为什么会同时出现 oItem.type = 0 和 oItem.children = 0
              res.push(oItem.id);
            }
        }
      }

      return res;
    },
    // 选择完知识库
    changeWiki(wikiIds) {
      let lists = _.cloneDeep(this.lists)
      lists[this.wikiIndex].wikiIds = wikiIds
      this.update(lists)
      this.$refs.wikiDialogRef.closeDialog();
      delete this.nums[this.wikiCurrentId]
      this.wikiIndex = 0
      this.wikiCurrentId = null
    },
    // 展示目录结构
    updateStatus(value, index) {
      let lists = _.cloneDeep(this.lists)
      lists[index].isShowWikiType = value
      this.update(lists)
    },
  },
  components: {
    draggable,
    [MFormSettingMark.name]: MFormSettingMark,
    MFormSettingReplaceImageDialog,
    MultilingualDialog,
    WikiDialog,
    FaultLibraryDialog,
  }
}
</script>

<style lang="scss">
.form-setting-panel {
  .mform-setting-photo-article-list {
    display: flex;
    flex-flow: column;
  }
}

.mform-setting-photo-article-list-header {
  padding: 0 16px;
  line-height: 22px;
  &-title {
    color: #595959;
  }
  &-subtitle {
    color: #8C8C8C;
    display: inline-block;
    font-size: 12px;
    margin-left: 12px;
  }
}

.mform-setting-photo-article-list-item {
  background-color: #fafafa;
  &-header {
    display: flex;
    justify-content: space-between;
    line-height: 22px;
    &-title {
      color: #BFBFBF;
    }
    &-delete {
      cursor: pointer;
      color: #8C8C8C;
      &:hover {
        color: $color-danger;
      }
    }
  }
}

.mform-setting-photo-article-list-item-content {
  display: flex;
  margin-top: 8px;
  .el-upload, .replace-image {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 3px;
    display: flex;
    height: 50px;
    width: 50px;
    line-height: 50px;
    cursor: pointer;

    img {
      width: 48px;
      height: 48px;
      position: relative;
      top: -2px;
    }
    i {
      width: 48px;
      line-height: 48px;
      font-size: 24px;
    }
  }
}

.mform-setting-photo-article-list-block {
  background-color: #fafafa;
  margin-top: 15px;
}

.mform-setting-photo-article-list-content-image {
  width: 40px;
  margin-right: 14px;
  .el-upload-list {
    display: none;
  }
}

.mform-setting-photo-article-list-content-main {
  flex: 1;
  .form-item {
    padding: 0 0 0 16px !important;;
  }
}

.mform-setting-photo-article-list-item-add-button {
  margin-top: 24px;
  margin-left: 16px;
  margin-right: 16px;
  margin-bottom: 32px;
  width: calc(100% - 32px);
  height: 40px;
}

.sortable-ghost {
  background-color: #fff;
}

.mform-setting-photo-article-list-item {
  cursor: move;
  padding: 15px 16px 0;
  &:hover {
    background-color: #fff;
  }
  .form-item {
    & > label {
      width: 50px;
    }
    & > .form-item-control {
      max-width: calc(100% - 50px);

      .form-item-control-content {
        display: flex;
        align-items: center;
      }
    }
  }
}

.mform-setting-photo-article-list-header-title {
  color: #595959;
}

.custom-link-item {
  .form-item-label-text {
    display: none;
  }
}
</style>

<style lang="scss" scoped>
.language-config {
  width: 32px;
  height: 28px;
  text-align: center;
  line-height: 28px;
  background: #F5F8FA;
  border-radius: 4px;
  border: 1px solid #CBD6E2;
  cursor: pointer;
  margin-left: 5px;
}

.event-link {
  font-size: 13px;
    color: #595959;
    margin: 0 0 10px 70px;

  span {
   color: $color-primary-light-6;
   cursor: pointer;
  }
}
</style>
